import { useEntityManager } from "@sker/core"
import { useData } from "@sker/runtime"
import { z } from "zod"

const sql = (type: string) => `
select
	*
from
	ks_live_room
where
	user_id IN (
	select
		room.user_id
	from
		ks_red_packet red
	left join ks_live_room room on
		room.id = red.room_id
	where
		red."type" = '${type}'
		and room.user_id notnull
	group by
		room.user_id 
)
order by online desc limit 200`

export default async () => {
    const input = z.object({
        type: z.optional(z.string())
    })
    const body = input.parse(useData())
    const type = body.type || '口令';
    const list: any[] = await useEntityManager(async m => {
        return m.query(sql(type), [])
    });
    if (list && list.length > 0) {
        // 去重
        const ids = new Set(list.map(it => it.user_id));
        return [...ids].map(id => list.find(it => it.user_id === id));
    }
    return list;
}